<?php
header("Content-type: text/html; charset=utf-8");

//获取$_GET或$_POST值
function getGP($var, $method = 'GP', $type = 'string') {
    $val;
    if ($method == 'G') {
        $val = isset($_GET[$var]) ? $_GET[$var] : '';
    } elseif ($method == 'P') {
        $val = isset($_POST[$var]) ? $_POST[$var] : '';
    } else {
        $val = isset($_GET[$var]) ? $_GET[$var] : ($_POST[$var] ? $_POST[$var] : '');
    }
    $val = trim($val);
    return ($type == 'string' ? (string) $val : intval($val));
}


function dump($obj){
    echo "<pre>";
    print_r($obj);
    echo "</pre>";

}


function jqAlert($msg,$url=""){
    if($url){
        echo '
	<script type="text/javascript">
		parent.window.jqAlert("'.$msg.'", "'. $url.'" );
	</script>
	';
    }else{
        echo '
	<script type="text/javascript">
		parent.window.jqAlert("'.$msg.'");
	</script>
	';
    }

}
function jqAlertnojs($msg,$url="",$title="华地百货"){
    if($url){
        echo '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>'.$title.'</title>
	<script src="js/jquery-2.1.1.min.js"></script>
	<script type="text/javascript" src="js/jqalert.js"></script>
	<link rel="stylesheet" href="css/css.css">

</head>
<body>
<script type="text/javascript">
		jqAlert("'.$msg.'", "'. $url.'" );
	</script>
	</body>
	</html>
	';
    }else{
        echo '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>华地百货</title>
	<script src="js/jquery-2.1.1.min.js"></script>
	<script type="text/javascript" src="js/jqalert.js"></script>
	<link rel="stylesheet" href="css/css.css">

</head>
<body>
<script type="text/javascript">
		jqAlert("'.$msg.'");
	</script>
	</body>
	</html>
	';
    }

}
function alert($msg) {

    //echo $msg;
    $args = func_get_args();
    if (!empty($msg)) {
        $alert = 'alert("' . $msg . '");';
    }
    if (count($args) >= 2) {

        if (empty($args[1])) {
            $jumpurl = 'history.back(-1);';
        } else {
            $jumpurl = 'top.location.href = "' . $args[1] . '";';
        }
//    } else {
//        $jumpurl = 'history.back();';
    // }else{
        //$jumpurl = 'history.back(-1);';
    }
    echo '
	<script type="text/javascript">
		' . $alert . '
		' . $jumpurl . '
	</script>
	';

    exit;
}

/*
 * 对话框提示函数
*/
function showmsg($msg, $url='0' , $isparent = 0)
{
	$alert	=	!empty( $msg ) ? 'alert("'.$msg.'");' : "";
	echo '<script type="text/javascript">'."\n".$alert."\n";
	if ( $url == "" ){
		echo 'history.back();';
	}elseif($url!='1'){
		if ( ! preg_match('#^https?://#i', $url))
		{
			$url = $url;
		}
		if ( $isparent==1 ){
			echo 'parent.window.location.href = "'.$url.'";';
		}else {
			echo 'window.location.href = "'.$url.'";';
		}
	}
	echo '</script>';
	exit;
}
function gb2utf8($str) {

    if (empty($str))
        return $str;

    return iconv('gbk//ignore', 'utf-8', $str);

    if (function_exists('iconv')) {
        return iconv('gbk//ignore', 'utf-8', $str);
    }

    if (function_exists('mb_convert_encoding')) {
        return mb_convert_encoding($str, 'gbk', 'utf-8');
    }
}

//UTF-8 转GB编码

function utf82gb($utfstr) {

    if (function_exists('iconv')) {
        return iconv('utf-8', 'gbk//ignore', $utfstr);
    }

    if (function_exists('mb_convert_encoding')) {
        return mb_convert_encoding($utfstr, 'utf-8', 'gbk');
    }
}
function redirect($url) {
	echo "<script>window.location.href='".$url."';</script>";
	exit;
}
/**

  +----------------------------------------------------------
 * 说明：重新封装两个数据库查询函数
 * 实现：查询数据，放入到二维数组中
 * 生成日期:2011-3-9
 * 生成人：lrli 349793000
 * 最后修改日期:2010-3-10
 * 最后修改人：lrli 349793000
  +----------------------------------------------------------
 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的二维数据
  +----------------------------------------------------------

 */
function fetch_array($sql) {
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
    $temp=array();
    foreach ($query->result_array() as $row) {
        $temp[]=$row;
    }
    return $temp;
}
/**

 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的二维数据
  +----------------------------------------------------------

 */
function fetch_count($sql) {
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
	return $query -> num_rows();
}

/**

  +----------------------------------------------------------
 * 说明：重新封装两个数据库查询函数
 * 实现：查询数据一条记录，放入到一维数组中
 * 生成日期:2011-3-9
 * 生成人：lrli 349793000
 * 最后修改日期:2010-3-10
 * 最后修改人：lrli 349793000
  +----------------------------------------------------------
 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的一维数据
  +----------------------------------------------------------
 */

function fetch_one_array($sql){
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
    $temp=array();
    $temp=$query->first_row('array');
    return $temp;

}
//是否合法Email地址
function is_email($email) {

    if (preg_match('/^[0-9a-z]+[0-9a-z_\.\-]*@[0-9a-z\-]+(\.[a-z]{2,4}){1,2}$/i', $email)) {
        return true;
    }
    return false;
}
/*
 * 检测输入网址的合法性
 */
function checkUrl($weburl)
{
  return !ereg("^http(s)*://[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$", $weburl);
}
//是否合法密码是否符合规则，字母与数字的组合
function is_password($password) {

    if (preg_match('/^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{3,}$/', $password)) {
        return true;
    }
    return false;
}
//是否电话号码
function is_mobile($string) {
    if(preg_match("/^(\d{3}-)(\d{8})$|^(\d{4}-)(\d{7})$|^(\d{4}-)(\d{8})$/",$string) || preg_match('/(13[0-9]|15[0-9]|18[0-9]|14[0-9])\d{8}$/',$string)) {
        return TRUE;
    }
    return FALSE;
}

function get_token_name($token)
{
	$sql="select name from token where token='".$token."' ";
	$res=fetch_one_array($sql);
	return $res['name'];

}
function getWxToken($token){
    $CI = get_instance();
    $CI->load->database();
    $sql="select * from token where token='".$token."' and expires_in >'".(time()-120)."' ";
    $num=fetch_count($sql);
    $res=fetch_one_array($sql);
    if($num>0){
        return $res['access_token'];
    }else{

        $sql_open = "select * from token where token = '$token' ";
        $opdata = fetch_one_array($sql_open);
        $wx=file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$opdata['appid'].'&secret='.$opdata['appsecret']);
        $token_json=json_decode($wx);
		$access_token=$token_json->access_token;
	    $sql="update token set access_token='$access_token',expires_in='".time()."' where token='".$token."'";
	    $query = $CI->db->query($sql);

        $this->db->update("token",array("access_token"=>$token_json->access_token,"expires_in"=>time()),"token = '$token'");
        return $token_json->access_token;
    }
}
function array_zh($arr)
{
	$re_value=array();
	for($e=0;$e<count($arr);$e++)
	{
			$re_arr[$e]=$arr[$e]['id'];
	}
	return $re_arr;
}
function qutiao_array($arr1,$arr2)
{
	$re_arr=array();
	$i=0;
	for($e=0;$e<count($arr1);$e++)
	{
		if(!in_array($arr1[$e],$arr2))
		{
			$re_arr[$i]=$arr1[$e];
			$i++;
		}
	}
	return $re_arr;
}
function Loadfile_wx($token,$pid,$sel_type)
{

		$sql_file_wx="select * from content where id='".$pid."' and wx_id!='' and ctime>='".(time()-259200)."' ";
	    $num=fetch_count($sql_file_wx);
		if($num>0)
		{
			$res=fetch_one_array($sql_file_wx);
			$re_value['errcode']=1;
			$re_value['media_id']=$res['wx_id'];
			$re_value['created_at']=$res['ctime'];
			$re_value['errmsg']="不更新数据";
			return $re_value;
		}else{
			$sql_file="select * from content where id='".$pid."'";
			$res_file=fetch_one_array($sql_file);
			switch($sel_type)
			{
				case "5":
					$type="image";
				break;
				case "6":
					$type="voice";
				break;
				case "7":
					$type="video";
				break;
			}
			$wx_token=getWxToken($token);
			$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$wx_token&type=$type";
			$post_data = array (
			    "media" => "@".$_SERVER['DOCUMENT_ROOT']."/bluewechat".$res_file['file_url']
			);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
			$output = curl_exec($ch);
	        $file_json=json_decode($output);
print_R($post_data);
			curl_close($ch);
			$re_value['errcode']=0;
			$re_value['media_id']=$file_json->media_id;
			$re_value['created_at']=$file_json->created_at;
			$re_value['errmsg']=$file_json->errmsg;

			return $re_value;
		}
}
function is_token($token)
{
	//token_type=1表示公众号，２表示订阅号
	$sql="select * from token where token='".$token."' and token_type='1'";
	$num=fetch_count($sql);
	return $num;
}

function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
     $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
		if($key!="name")
		{
	            $array[$key] = $value;
		}else{
	        if (is_array($value)) {
	            arrayRecursive($array[$key], $function, $apply_to_keys_also);
	        } else {
	            $array[$key] = $function($value);
	        }
	   }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}
	function dataPost($post_string, $url)
	{//POST方式提交数据
		 $context = array ('http' => array ('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", 'content' => $post_string ) );
		 $stream_context = stream_context_create ( $context );
		 $data = file_get_contents ( $url, FALSE, $stream_context );
		 return $data;
	 }
/*
 * 根据数据类型取出不同的数据
 */
	function get_log_type($typeres)
	{
		$re_value="";
		switch($typeres['type'])
		{
			case "2":
				$sql="select * from news where list_id='".$typeres['id']."'";
				$res=fetch_array($sql);
				$re_value .="单图:";
				foreach($res as $key=>$row)
				{
					if($key!=0) $re_value .="<br>";
					$re_value .=$res['url'];
				}
				break;
			case "3":
				$sql="select * from news where list_id='".$typeres['id']."'";
				$res=fetch_array($sql);
				$re_value .="多图:";
				foreach($res as $key=>$row)
				{
					if($key!=0) $re_value .="<br>";
					$re_value .=$res['url'];
				}
				break;
			case "4":
				$sql="select * from processes where id='".$typeres['id']."'";
				$res=fetch_array($sql);
				foreach($res as $key=>$row)
				{
					if($key!=0) $re_value .="<br>";
					$re_value .=$res['name'];
				}
			break;
			case "5":
			case "6":
			case "7":
				$sql="select * from content where id='".$typeres['id']."'";
				$res=fetch_one_array($sql);
				$re_value=$res['url'];
			break;
		}
		return $re_value;
	}


//返回是否置顶的文字
function gettopstr($n){
    $topres=array(1=>"置顶",0=>'-');
    return $topres[$n];
}

//返回是否状态的文字
function getstatusstr($n){
    $status=array(1=>'<font color="#0f0">正常</font>',0=>'删除',2=>'<font color="#666">隐藏</font>');
    return $status[$n];
}

function getstatusstr2($n){
    $status=array(1=>'<font color="#0f0">上线</font>',0=>'删除',2=>'<font color="#666">下线</font>');
    return $status[$n];
}

//MD5加盐
function domd5($data){
    return md5(md5($data)."spr_dfjlj");
}

//检查openid和salt
function chopenid($openid,$salt){
    if($openid =="" || $salt ==""){
        return false;
    }
    $res=fetch_one_array("select * from web_user where openid='".$openid."' ");
    if($salt==domd5($res['salt'])){
        //保存
        if($openid) {
            setcookie("openid", $openid, time() + 3600 * 24 * 360);
        }
        if($salt){
            setcookie("salt", $salt, time()+3600*24*360);
        }

        return true;
    }else{
        return false;
    }

}

//检查openid和salt
function chopenid_serve($openid,$salt){
    if($openid =="" || $salt ==""){
        return false;
    }
    $res=fetch_one_array("select * from web_user_serve where openid_serve='".$openid."' ");

    if($salt==domd5($res['salt'])  || $salt==$res['salt'] ){
        //保存
        if($openid) {
            setcookie("openid_serve", $openid, time() + 3600 * 24 * 360);
        }
        if($salt){
            setcookie("salt_serve", $salt, time()+3600*24*360);
        }

        return true;
    }else{
        return false;
    }


}


//获取楼层的名称
function getFloorName($fid){
    $fid=intval($fid);
    $res=fetch_one_array("select * from web_floor where id='".$fid."'");
    return $res['floor'];
}

//获取用户的hyid
function getHyidByOpenid($openid){

}

function getMdidByToken($token){
    $res=fetch_one_array("select * from web_in_store where token='".$token."'");
    return $res['mdid'];
}

//获得openid
function getOpenid(){
    $openid=getGP("openid")?getGP("openid"):$_COOKIE["openid"];
    if($openid){
        setcookie("openid", $openid, time()+3600*24*360);
    }
    return $openid;
}
//token
function getToken(){
    $token=getGP("token")?getGP("token"):$_COOKIE["token"];
    if($token){
        setcookie("token", $token, time()+3600*24*360);
    }
    return $token;
}
//获得openid
function getGzh(){
    $gzh=getGP("gzh")?getGP("gzh"):$_COOKIE["gzh"];
    if($gzh){
        setcookie("gzh", $gzh, time()+3600*24*360);
    }
    return $gzh;
}
//获得openid
function getSalt(){
    $salt=getGP("salt")?getGP("salt"):$_COOKIE["salt"];
    if($salt){
        setcookie("salt", $salt, time()+3600*24*360);
    }
    return $salt;
}

//获取title
function getStoreConfig($token,$field){
    $res=fetch_one_array("select * from web_storeconfig where token='".$token."' ");

    if($field=="title"){
        return $res[$field]?$res[$field]:"华地百货";
    }else{
        return $res[$field]?$res[$field]:"";
    }

}


//获取品牌的活动数量
function getBrandActiveCount($bid){
    $ntime=date("Y-m-d H:i:s");
    $res=fetch_one_array("select count(*) as num from web_activity a,web_brand b where 1  and a.bid='" . $bid . "'  and a.bid=b.id and b.status=1 and a.status=1 and a.stime<='".$ntime."' and a.etime>='".$ntime."' ");
    return $res["num"];



}

//插入授权加跳地址
function insWxloginBack($burl){
    if($burl){
        $CI = get_instance();
        $CI->load->database();
        $inburldata=array(
            'url'=>$burl,
            'ctime'=>date("Y-m-d H:i:s")
        );
        $CI->db->insert('web_wxlogin_back', $inburldata);
        $urlid=$CI->db->insert_id();
    }else{
        $urlid=0;
    }
    return $urlid;
}


//获取授权回跳地址
function getWxloginBack($id){
    $res=fetch_one_array("select * from web_wxlogin_back where id='".$id."' limit 1");
    if($res){
        return $res["url"];
    }else{
        return "/";
    }
}



//更新服务号的token
function upTokenServe(){
    $CI = get_instance();
    $CI->load->database();
    $wx=fetch_one_array("select * from token_serve where 1 ");
    if(!$wx["access_token"] || $wx["expires_in"]<time()-7000){
        $appid=$wx["appid"];
        $secret=$wx["appsecret"];

        $token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."");
        $token=json_decode($token);
        if($token->access_token) {
            $upt = array(
                "access_token" => $token->access_token,
                "expires_in" => time()
            );
            $CI->db->update('token_serve', $upt, "id = 1 ");
        }
    }

}

//保存留资总表数据
function saveLiuZi($name,$tel,$typestr,$forid){
    $CI = get_instance();
    $CI->load->database();
    $idt = array(
        "name" => $name,
        "tel" => $tel,
        "typestr" => $typestr,
        "forid" => $forid,
        "ctime" => date("Y-m-d H:i:s")
    );
    $CI->db->insert('web_liuzi', $idt);
}


function http_request($url,$timeout=30,$header=array()){
    if (!function_exists('curl_init')) {
        throw new Exception('server not install curl');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    $data = curl_exec($ch);
    list($header, $data) = explode("\r\n\r\n", $data);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        $matches = array();
        preg_match('/Location:(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $data = curl_exec($ch);
    }

    if ($data == false) {
        curl_close($ch);
    }
    @curl_close($ch);
    return $data;
}


function getwxuser($openid,$field=""){
    $res=fetch_one_array("select * from web_user_serve where openid='".$openid."' or openid_serve ='".$openid."' ");

    if($field){
        return $res[$field];
    }else{
        return $res;
    }

}


?>